package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/longest-common-subsequence/
 */
public class Title1143 {

    /**
     * 最长公共子序列(子序列不连续）
     * dp[i][j]表示：以下标i-1为末尾的A，以下标j-1为末尾的B，最长公共子序列长度为dp[i][j]
     * 递推公式：
     * 
     *         if(text1.charAt(i-1) == text2.charAt(i-2)) dp[i][j] = Math.max(dp[i][j],dp[i-1][j-1] + 1);
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence(String text1, String text2) {
        int[][] dp = new int[text1.length() + 1][text2.length() + 1];
        int max = 0;
        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
                if (dp[i][j] > max) {
                    max = dp[i][j];
                }
            }
        }
        return max;
    }




    public int longestCommonSubsequence22(String text1, String text2) {
        //dp[i][j]表示下标为i-1,j-1时最长公共子序列的长度
        int n = text1.length();
        int m = text2.length();
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    //二者不相等
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[n][m];
    }









    public static void main(String[] args) {

    }
}
